package com.common.demo.exception;

import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MyClassloader extends ClassLoader{
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classPath = "file:///E:/project/common-demo/target/classes/"+name.replace(".","/")+".class";
        byte[] allBytes = null;
        try {
            Path path = Paths.get(new URI(classPath));
            allBytes = Files.readAllBytes(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defineClass(name,allBytes,0,allBytes.length);
    }

    public static void main(String[] args) {
        MyClassloader classloader = new MyClassloader();
        try {
            Class<?> aClass = classloader.findClass("com.common.demo.exception.CommonBean");
            Object o = aClass.newInstance();
            Method toString = aClass.getMethod("toString");
            System.out.println((String)toString.invoke(o));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
